package main

import (
	"flag"
	"fmt"
	"go_learn/gopl/ch8/utils"
	"os"
	"sync"
	"time"
)

func main() {

	flag.Parse()
	roots := flag.Args()
	if len(roots) == 0 {
		roots = []string{"."}
	}

	fileSizes := make(chan int64)

	var wg sync.WaitGroup

	for _, root := range roots {
		wg.Add(1)
		go utils.WalkDir(root, &wg, fileSizes)
	}

	go func() {
		wg.Wait()
		close(fileSizes)
	}()

	var nfiles, nbytes int64
	for size := range fileSizes {
		nfiles++
		nbytes += size
	}
	printDiskUsage(nfiles, nbytes)
}

func printDiskUsage(nfile, nbytes int64) {
	fmt.Printf("%d files %d KB\n", nfile, nbytes)
}

func selectDemo() {
	abort := make(chan struct{})
	go func() {
		os.Stdin.Read(make([]byte, 1))
		abort <- struct{}{}
	}()

	select {
	case <-time.After(10 * time.Second):
		fmt.Println("Go")
		return
	case <-abort:
		fmt.Println("Launch abort")
		return
	}
}

func selectDemo2() {
	// 只有一次缓存区，下面进入channel只有一次机会，然后释放，往复循环，只有0，2，4，6，8能在里面
	ch := make(chan int, 1)
	for i := 0; i < 10; i++ {
		select {
		case x := <-ch:
			fmt.Println(x)
		case ch <- i:
		}
	}
}

func selectDemo3() {
	fmt.Println("countdown. parse any words abort!")
	// 返回值是一个channel，按照设定的时间作为间隔，给channel中发送时间作为channel中的元素
	tick := time.Tick(1 * time.Second)
	abort := make(chan struct{})
	go func() {
		os.Stdin.Read(make([]byte, 1))
		abort <- struct{}{}
	}()
	for i := 0; i < 10; i++ {
		select {
		case x := <-tick:
			fmt.Println(x)
		case <-abort:
			fmt.Println("Launch abort")
			return
		}
	}
}

